#include "../include/head.h"
#include <libgen.h>

// 服务端链栈
typedef struct node_S
{
    char subpath[128];
    struct node_S* front;
    struct node_S* back; 
} pathNode;

typedef struct 
{
    pathNode* head;
    pathNode* tail;
    int size;
}pathStack;

pathStack* pathStack_init()
{ 
    pathStack *p=(pathStack*)calloc(1,sizeof(pathStack));
    ERROR_CHECK(p, NULL, "pathstack calloc");
    return p;
}

int pathStack_print(pathStack* p,char* str)
{
    pathNode *cur=p->head;
    for(int i=0;i<p->size;i++){
        memcpy(str, "/", 1);
        str += 1;
        memcpy(str, cur->subpath, strlen(cur->subpath));
        str += strlen(cur->subpath);
        cur = cur->back;
    }

    return 0;
}

int pathStack_push(pathStack *stack,char *subpath){
    pathNode* node=(pathNode* )calloc(1,sizeof(pathNode));
    memcpy(node->subpath,subpath,strlen(subpath));
    node->back = NULL;
    node->front = NULL;

    if(stack->size==0) {
        stack->head=node;
        stack->tail=node;
    }else{
        node->front=stack->tail; //新节点指向当前节点的
        stack->tail->back=node;  //当前节点的back指向新节点
        stack->tail=node;        //更新最后节点。
    }
    stack->size++;
    return 0;
}

int pathStack_pop(pathStack *stack){
    if(stack->size==0) return 0;
    pathNode *node=stack->tail; 

    if(stack->size == 1) {
        stack->head = NULL;
        stack->tail = NULL;
    }
    else
    {
        stack->tail=node->front;
        stack->tail->back = NULL;
    }
    free(node);
    stack->size--;
    return 0;
}

int pathStack_destory(pathStack *pstack) {
    while (pstack->size != 0)
    {
        // printf("当前栈长 = %d\n", pstack->size);
        pathStack_pop(pstack);
    }

    return 0;
}

// 这是getTruePath的实现函数
int pathTostack(char *path, pathStack *pstack, MYSQL *mysql, ResponsePackage *presponse, int netfd);
int nowpathTostack(int now_path_id, MYSQL *mysql, pathStack *pstack);
int checkUser(int user_id, char *args, int args_len, MYSQL *mysql,
              ResponsePackage *presponse, int netfd);

/**
 * @brief remove可以删除任意路径的文件，可以是相对路径，也可以是绝对路径
 */
int server_rmfile(MYSQL *mysql, int args_len, char *args, int netfd, Client_info *pclient_info, pthread_mutex_t *mutex, int now_path_id, int user_id) {
    char op_args[256];
    sprintf(op_args, "%s %s", "RMFILE", args);
    // printf("%s\n", op_args);
    // mysql select取得当前path
    ResponsePackage response;
    
    bzero(&response, sizeof(response));
    // pathStack *pstack = pathStack_init();
    char sql[256] = {0};
    char truepath[128] = {0};
    int ret = getTruePath(user_id, now_path_id, args, args_len, mysql, &response, truepath, netfd);
    if(ret == -1) return -1;
    // 测试用
    // printf("要删除的目标文件的绝对路径是%s \n", truepath);
    // 查表是否是文件且存在，若存在该表发正确包，若不存在发错误包
    bzero(sql, sizeof(sql));
    snprintf(sql, sizeof(sql), "select file_dir_type from fd_data where path = '%s'", truepath);
    // bug: 这里没有做mysql_query,导致mysql_num_rows出现段错误
    int qret = mysql_query(mysql, sql);
    MYSQL_ERROR_CHECK(qret, 0, mysql, "server_rmfile: mysql_query select file_dir_type");
    MYSQL_RES *psqlRes = mysql_store_result(mysql);
    if(mysql_num_rows(psqlRes) == 0) {
        // 说明该文件不存在
        response.type = DIR_ERR;
        ssize_t sret = snprintf(response.args_val, sizeof(response.args_val), "当前目录找不到%s文件，请输入正确的文件名!", args);
        response.args_len = sret;
        send(netfd, &response.type, sizeof(response.type), MSG_NOSIGNAL);
        send(netfd, &response.args_len, sizeof(response.args_len), MSG_NOSIGNAL);
        send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);
        mysql_free_result(psqlRes);
        return -1;
    } else {
        MYSQL_ROW row = mysql_fetch_row(psqlRes);
        int file_dir_type = atoi(row[0]);
        // int is_delete = atoi(row[1]);
        // 测试信息
        // printf("%s: file_dir_type = %d\n", truepath, file_dir_type);
        if(file_dir_type == is_Dir) {
            // 说明目标是目录，而不是文件，发错误包
            response.type = DIR_ERR;
            ssize_t sret = snprintf(response.args_val, sizeof(response.args_val),
                                    "删除的目标是目录，请使用rmdir命令!");
            response.args_len = sret;
            send(netfd, &response.type, sizeof(response.type), MSG_NOSIGNAL);
            send(netfd, &response.args_len, sizeof(response.args_len), MSG_NOSIGNAL);
            send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);
            mysql_free_result(psqlRes);
            return -1;        
        } else {
            // if(is_delete == 1) {
            //     // 说明该文件已被删除过，因此不存在
            //     response.type = DIR_ERR;
            //     ssize_t sret = snprintf(response.args_val, sizeof(response.args_val),
            //                             "%s该文件已被删除，请不要重复删除!", args);
            //     response.args_len = sret;
            //     send(netfd, &response.type, sizeof(response.type), MSG_NOSIGNAL);
            //     send(netfd, &response.args_len, sizeof(response.args_len), MSG_NOSIGNAL);
            //     send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);
            //     mysql_free_result(psqlRes);
            //     return -1;
            // } else {
            pthread_mutex_lock(mutex);
            int true_user_id = pclient_info[netfd].belongs_to_userid;
            if(true_user_id != user_id) {
                printf("处理的是旧包，以上操作无效！\n");
                pthread_mutex_unlock(mutex);
                return -1;
            }
            pthread_mutex_unlock(mutex);
            bzero(sql, sizeof(sql));
            snprintf(sql, sizeof(sql), "delete from fd_data where path = '%s'", truepath);
            int mysql_qret = mysql_query(mysql, sql);
            MYSQL_ERROR_CHECK(mysql_qret, 0, mysql, "mysql_query: delete path");
            response.type = REMOVE_SUCCESS;
            ssize_t sret = snprintf(response.args_val, sizeof(response.args_val), 
                                    "%s已经被成功删除!", args);
            response.args_len = sret;
            send(netfd, &response.type, sizeof(response.type), MSG_NOSIGNAL);
            send(netfd, &response.args_len, sizeof(response.args_len), MSG_NOSIGNAL);
            send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);
            // }
        }
    }
    mysql_free_result(psqlRes);
    return 0;
}

int server_cd(MYSQL *mysql, int args_len, char *args, int netfd, 
              Client_info *pclient_info, pthread_mutex_t *pmutex, int now_path_id, int user_id) {
    // 先得到最终的完整路径，再去判断user_id，id, path等信息

    char op_args[256];
    sprintf(op_args, "%s %s", "CD", args);

    ResponsePackage response;
    bzero(&response, sizeof(response));

    char sql[256] = {0};
    char truepath[128] = {0};
    int pathret = getTruePath(user_id, now_path_id, args, args_len, mysql, &response, truepath, netfd);
    if(pathret == -1) {
        return -1;
    }

    bzero(sql, sizeof(sql));
    // snprintf(sql, sizeof(sql), "select id, user_name from fd_data where path = '%s'", truepath);
    snprintf(sql, sizeof(sql), "select id, file_dir_type from fd_data where path = '%s'", truepath);
    int ret = mysql_query(mysql, sql);
    MYSQL_ERROR_CHECK(ret, 0, mysql, "mysql_query id in server_cd");
    // 这里一定可以得到id和user_name，为了单元测试，需要打印一下
    MYSQL_RES *psqlRes = mysql_store_result(mysql);
    if(mysql_num_rows(psqlRes) == 0) {
        printf("mysql_store_result 出错! \n");
        exit(-1);
    }
    MYSQL_ROW row = mysql_fetch_row(psqlRes);
    int new_path_id = atoi(row[0]);
    int type = atoi(row[1]);
    mysql_free_result(psqlRes);
   
    // bug: 需要加一个判断，目标路径是文件还是目录
    if(type == is_File) {
        // 这是文件，需要抛弃
        printf("目标路径%s是一个文件，不是目录! \n", truepath);
        response.type = DIR_ERR;
        ssize_t sret = snprintf(response.args_val, sizeof(response.args_val), "%s", "目标路径是一个文件，不是目录，请输入正确路径！");
        response.args_len = sret;
        send(netfd, &response.type, sizeof(response.type), MSG_NOSIGNAL);
        send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
        send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);
        return -1;
    }

    pthread_mutex_lock(pmutex);
    int true_user_id = pclient_info[netfd].belongs_to_userid;
    if(true_user_id != user_id) {
        printf("发送该请求的用户已断开连接，以上操作无效!\n");
        pthread_mutex_unlock(pmutex);
        // pathStack_destory(pstack);
        return -1;
    }
    pclient_info[netfd].now_path_id = new_path_id;
    pthread_mutex_unlock(pmutex);
    response.type = CD_SUCCESS;
    ssize_t sret = snprintf(response.args_val, sizeof(response.args_val), "%s", truepath);
    response.args_len = sret;
    send(netfd, &response.type, sizeof(response.type), MSG_NOSIGNAL);
    send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
    send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL); 

    return 0;
}

int checkUser(int user_id, char *args, int args_len, MYSQL *mysql,
              ResponsePackage *presponse, int netfd) {
    // 只需要针对绝对路径判断，根目录的用户名是否与当前登录用户相同
    char sql[256] = {0};
    snprintf(sql, sizeof(sql), "select user_name from user_data where user_id = %d", user_id);
    int qret = mysql_query(mysql, sql);
    MYSQL_ERROR_CHECK(qret, 0, mysql, "checkUser: mysql_query select user_name");
    MYSQL_RES *psqlRes = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(psqlRes);
    char username[128] = {0};
    snprintf(username, sizeof(username), "%s", row[0]);
    mysql_free_result(psqlRes);
    // bug: 这里没有初始化为0
    char args_path[128] = {0};
    memcpy(args_path, args, args_len);
    char *token, *savepath;
    // bug
    token = strtok_r(args_path, "/", &savepath);
    if(token == NULL || strcmp(token, username) != 0) {
        printf("checkuser()输入的根目录不对!\n");
        presponse->type = DIR_ERR;
        ssize_t sret = snprintf(presponse->args_val, sizeof(presponse->args_val), "%s", "根目录用户名输入错误，请输入包含正确根目录的路径名");
        presponse->args_len = sret;
        send(netfd, &presponse->type, sizeof(presponse->type), MSG_NOSIGNAL);
        send(netfd, &presponse->args_len, sizeof(int), MSG_NOSIGNAL);
        send(netfd, presponse->args_val, presponse->args_len, MSG_NOSIGNAL);
        return -1;
    }
    return 0;
}

int getTruePath(int user_id, int now_path_id, char *args, int args_len, MYSQL *mysql, 
                ResponsePackage *presponse, char *truepath, int netfd)
{
    pathStack *pstack = pathStack_init();   // 不要忘记释放链栈，每个新的用户的连接，都需要新的链栈
    char args_path[128] = {0};              // 参数路径
    memcpy(args_path, args, args_len);

    // char sql[256] = {0};
    if(args_path[0] == '/') {
        // 绝对路径
        // 需要验证绝对路径的根目录是否正确
        int ret = checkUser(user_id, args, args_len, mysql, presponse, netfd);
        if(ret == -1) {
            pathStack_destory(pstack);
            return -1;
        }
        ret = pathTostack(args_path, pstack, mysql, presponse, netfd);
        if(ret == -1) {
            pathStack_destory(pstack);
            return -1;
        }
    } else {
        // 1. now_path_id 得到当前路径path, 2. 将nowpath通过strtok_r循环切割到stack中
        nowpathTostack(now_path_id, mysql, pstack);
        // 3. 通过strtok_r不断将相对路径放到当前路径中
        int ret = pathTostack(args_path, pstack, mysql, presponse, netfd);
        if(ret == -1) {
            pathStack_destory(pstack);
            return -1;
        }
    }
    // 此时得到的是正确的路径，但是不知道是不是当前用户的
    pathStack_print(pstack, truepath);
    printf("truepath = %s \n", truepath);
    pathStack_destory(pstack);
    printf("弹栈完成\n");
    return 0;
}

int nowpathTostack(int now_path_id, MYSQL *mysql, pathStack *pstack) {
    // 1. select取出当前路径
    // 数据库名字写错了，应该是fd_data，而不是fa_data
    char nowpath[128] = {0};
    char sql[256] = {0};
    snprintf(sql, sizeof(sql), "select path from fd_data where id = %d;", now_path_id);
    int ret = mysql_query(mysql, sql);
    MYSQL_ERROR_CHECK(ret, 0, mysql, "nowpathTostack(): mysql_query select path in");
    MYSQL_RES *psqlRes = mysql_store_result(mysql);
    // 默认是当前目录结构不会发生改变，一定可以找到当前目录
    MYSQL_ROW row = mysql_fetch_row(psqlRes);
    snprintf(nowpath, sizeof(nowpath), "%s", row[0]);
    // printf("当前目录路径是%s \n", nowpath);
    mysql_free_result(psqlRes);
    // 2. 将当前目录放到链栈中
    char *token, *savepath;
    for(char *path = nowpath; ; path = NULL) {
        token = strtok_r(path, "/", &savepath);
        if(token == NULL) break;
        else {
            pathStack_push(pstack, token);
        }
    }

    return 0;
}

// 该函数是将参数路径，一个一个切出来然后拼接到实际路径中，如果通过查表能够查到结果，那么就入栈，然后拼到实际路径中
int pathTostack(char *path, pathStack *pstack, MYSQL *mysql, ResponsePackage *presponse, int netfd) {
    char uncompletedPath[128] = {0};
    char *token, *savepath;
    for(char *temPath = path; ; temPath = NULL) {
        token = strtok_r(temPath, "/", &savepath);
        // 将subpath切割出来后，需要分情况讨论是否需要
        if(token == NULL) break;
        // bug: strcmp()之后没有写 == 0，就直接进入了
        else if(strcmp(token, ".") == 0) continue;
        else if(strcmp(token, "..") == 0) {
            if(pstack->size == 1 || pstack->size == 0) {
                // 即使是遇到/../../这种错误输入，也可以避免
                continue;   // 因为/usr才是根目录，不能删除usr
            } else {
                pathStack_pop(pstack);
            }
        } else {
            // 得到当前的目录
            bzero(uncompletedPath, sizeof(uncompletedPath));
            pathStack_print(pstack, uncompletedPath);
            snprintf(uncompletedPath + strlen(uncompletedPath), sizeof(uncompletedPath) - strlen(uncompletedPath), "/%s", token);
            char sql[256] = {0};
            snprintf(sql, sizeof(sql), "select is_delete from fd_data where path = '%s'", uncompletedPath);
            int ret = mysql_query(mysql, sql);
            MYSQL_ERROR_CHECK(ret, 0, mysql, "mysql_query in pathTostack");
            MYSQL_RES *psqlRes = mysql_store_result(mysql);
            if(mysql_num_rows(psqlRes) == 0) {
                // 说明没有找到目标路径，输入的路径有问题
                presponse->type = DIR_ERR;
                ssize_t sret = snprintf(presponse->args_val, sizeof(presponse->args_val), "%s", "没有找到目标路径，请重新输入正确路径!");
                presponse->args_len = sret;
                send(netfd, &presponse->type, sizeof(presponse->type), MSG_NOSIGNAL);
                send(netfd, &presponse->args_len, sizeof(int), MSG_NOSIGNAL);
                send(netfd, presponse->args_val, presponse->args_len, MSG_NOSIGNAL);
                return -1;
            } else {
                // 说明找到目标路径
                MYSQL_ROW row = mysql_fetch_row(psqlRes);
                int is_delete = atoi(row[0]);
                printf("当前检测目录为%s, is_delete = %d \n", uncompletedPath, is_delete);
                if(is_delete == 0) {
                    pathStack_push(pstack, token);
                    // // 一点点将正确路径放在truepath中，实际的正确路径已经存放在了stack栈中，如果是../..的情况
                    // 仍然需要在else if(..)的时候更新truepath，truepath与pstack是具有相同的功能，因此没有必要使用truepath参数
                    // sret = snprintf(truepath + sret, sizeof(truepath) - sret, "/%s", token);
                } else {
                    // 说明目标路径已经被删除
                    presponse->type = DIR_ERR;
                    ssize_t sret = snprintf(presponse->args_val, sizeof(presponse->args_val), "%s", "目标文件已经被删除，请重新输入正确路径!");
                    presponse->args_len = sret;
                    send(netfd, &presponse->type, sizeof(presponse->type), MSG_NOSIGNAL);
                    send(netfd, &presponse->args_len, sizeof(int), MSG_NOSIGNAL);
                    send(netfd, presponse->args_val, presponse->args_len, MSG_NOSIGNAL);
                    return -1;
                }
            }
            mysql_free_result(psqlRes); // 不能忘记释放资源
        }
    }

    return 0;
}

// void test_server_cd(void) {
//     MYSQL *mysql = mysql_init(NULL);
//     MYSQL *pret = mysql_real_connect(mysql, "localhost", "admin", "123456", "user_base", 0, NULL, 0);
//     if(pret == NULL) {
//         fprintf(stderr, "%s:%s", "mysql_real_connect", mysql_error(mysql));
//         return;
//     }
//     char args[128] = {0};
//     printf("Please input a directory to test: \n");
//     scanf("%s", args);
//     int args_len = strlen(args);
//     Client_info client_info[2];
//     client_info[0].belongs_to_userid = 2;
//     client_info[0].now_path_id = 3;
//     pthread_mutex_t mutex;
//     pthread_mutex_init(&mutex, NULL);
//     int user_id = 2;
//     int now_path_id = 3;

//     server_cd(mysql, args_len, args, 0, client_info, &mutex, now_path_id, user_id);
// }

// void test_server_rmfile(void) {
//     MYSQL *mysql = mysql_init(NULL);
//     MYSQL *pret = mysql_real_connect(mysql, "localhost", "admin", "123456", "user_base", 0, NULL, 0);
//     if(pret == NULL) {
//         fprintf(stderr, "%s:%s", "mysql_real_connect", mysql_error(mysql));
//         return;
//     }
//     char args[128] = {0};
//     printf("Please input a file to test: \n");
//     scanf("%s", args);
//     int args_len = strlen(args);
//     Client_info client_info[2];
//     client_info[0].belongs_to_userid = 2;
//     client_info[0].now_path_id = 4;
//     pthread_mutex_t mutex;
//     pthread_mutex_init(&mutex, NULL);
//     int user_id = 2;
//     int now_path_id = 4;

//     server_rmfile(mysql, args_len, args, 0, client_info, &mutex, now_path_id, user_id);
// }

// int main() {
//     // test_server_cd();
//     test_server_rmfile();

//     return 0;
// }

//ls在这个版本只会成功
int server_ls(MYSQL *mysql, int args_len, char *args, int netfd, Client_info *pclient_info, pthread_mutex_t *mutex, int now_path_id, int user_id){
    char op_args[256];
    sprintf(op_args, "%s %s", "LS", args);
    
    ResponsePackage response;
    bzero(&response, sizeof(response));
    char sql[1024] = {0};
    snprintf(sql, sizeof sql, "select file_dir_name from fd_data where p_id = %d and is_delete = 0",now_path_id );
    mysql_query(mysql, sql);

    MYSQL_RES *rows = mysql_store_result(mysql);
    int currnum = 0;
    for(unsigned int i = 0; i < mysql_num_rows(rows); i++){
        MYSQL_ROW row = mysql_fetch_row(rows);
        int n = snprintf(response.args_val + currnum, sizeof response.args_val - currnum, "%s\t",row[0]);
        currnum += n;
    }
    //准备send数据
    response.args_len = currnum;                                               
    printf("%s\n", response.args_val);
    response.type = LS_SUCCESS;
    pthread_mutex_lock(mutex);
    int true_user_id = pclient_info[netfd].belongs_to_userid;
    if(true_user_id != user_id) {
        printf("发送该请求的用户已断开连接，以上操作无效!\n");
        pthread_mutex_unlock(mutex);
        return -1;
    }
    pthread_mutex_unlock(mutex);

    send(netfd, &response.type, sizeof(MSG_TYPE), MSG_NOSIGNAL);
    send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
    send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);
    return 0;
}




int split_path(const char *input, char **out_parent, char **out_name) {
    if (!input || !out_parent || !out_name) return -1;

    // 去掉末尾多余的 '/'
    size_t len = strlen(input);
    while (len > 1 && input[len - 1] == '/') {
        len--;
    }

    char *tmp = (char *)malloc(len + 1);
    if (!tmp) return -1;
    memcpy(tmp, input, len);
    tmp[len] = '\0';

    // 找最后一个 '/'
    char *slash = strrchr(tmp, '/');
    if (!slash) {
        // 没有 '/'，父路径为 "."
        *out_parent = strdup(".");
        *out_name   = strdup(tmp);
    } else if (slash == tmp) {
        *out_parent = strdup("/");
        *out_name   = strdup(slash + 1);
    } else {
        *slash = '\0';
        *out_parent = strdup(tmp);
        *out_name   = strdup(slash + 1);
    }

    free(tmp);
    if (!*out_parent || !*out_name) {
        free(*out_parent);
        free(*out_name);
        return -1;
    }
    return 0;
}







int server_mkdir(MYSQL *mysql, int args_len, char *args, int netfd, Client_info *pclient_info, pthread_mutex_t *mutex, int now_path_id, int user_id){
    char op_args[256];
    sprintf(op_args, "%s %s", "MKDIR", args);
    
    ResponsePackage response;
    bzero(&response, sizeof response);
    char sql[4096] = {0};
    char args_buf[1024] = {0};
    memcpy(args_buf, args, args_len);

    char truepath[256] = {0};
    char *parent = NULL, *name = NULL;
    //找到目录名字
    if (split_path(args, &parent, &name) != 0) {
        fprintf(stderr, "路径校验失败\n");
        free(parent); free(name);
        return 1;
    }
    printf("%s,%s\n", parent, name);
    if(getTruePath(user_id, now_path_id, parent, args_len, mysql, &response, truepath, netfd)){
        return -1;
    }
    int trueid = 0;
    bzero(sql, sizeof(sql));
    snprintf(sql, sizeof sql, "select id from fd_data where path = '%s' and file_dir_type = %d and is_delete = 0",truepath,is_Dir);
    printf("%s\n", sql);
    mysql_query(mysql, sql);
    MYSQL_RES *res = mysql_store_result(mysql);
    MYSQL_ROW row_pre = mysql_fetch_row(res);
    unsigned long num_rows = mysql_num_rows(res);
    printf("%s\n", row_pre[0]);
    trueid = atoi(row_pre[0]);
    printf("查到 %lu 行\n", num_rows);



    //1.查找数据库的当前目录有没有重名目录
    //  没有：创建一个目录的表项
    bzero(sql, sizeof(sql));
    snprintf(sql, sizeof sql, "select id,is_delete from fd_data where p_id = %d and file_dir_name = '%s' and file_dir_type = %d",trueid,name,is_Dir);
    printf("%s\n", sql);
    mysql_query(mysql, sql);
    res = mysql_store_result(mysql);
    row_pre = mysql_fetch_row(res);
    num_rows = mysql_num_rows(res);
    printf("查到 %lu 行\n", num_rows);
    //2.有：send错误包，并打印错误原因
    if(num_rows != 0 && atoi(row_pre[1]) == 0){
        response.type = DIR_ERR;
        snprintf(response.args_val, sizeof response.args_val, "The same directory already exists\n");
        response.args_len = strlen (response.args_val);
        printf("%s\n", response.args_val);
        pthread_mutex_lock(mutex);
        int true_user_id = pclient_info[netfd].belongs_to_userid;
        if(true_user_id != user_id) {
            printf("发送该请求的用户已断开连接，以上操作无效!\n");
            pthread_mutex_unlock(mutex);
            return -1;
        }
        pthread_mutex_unlock(mutex);
        send(netfd, &response.type, sizeof(MSG_TYPE), MSG_NOSIGNAL);
        send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
        send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);
        free(parent);
        free(name);
        mysql_free_result(res);
        return -1;
        //3.如果存在该目录就复用这个目录，因为path是唯一键，不可以重复，在rmdir中只能删空目录
    }else if(num_rows != 0 && atoi(row_pre[1]) == 1){
        printf("如果存在该目录就复用这个目录");
        bzero(sql, sizeof sql);
        snprintf(sql, sizeof sql, "update fd_data set is_delete = 0 where id = %d",atoi(row_pre[0]));
        mysql_query(mysql, sql);
        //准备send数据
        response.type = MKDIR_SUCCESS;
        response.args_len = 0;
        pthread_mutex_lock(mutex);
        int true_user_id = pclient_info[netfd].belongs_to_userid;
        if(true_user_id != user_id) {
            printf("发送该请求的用户已断开连接，以上操作无效!\n");
            pthread_mutex_unlock(mutex);
            free(parent);
            free(name);
            mysql_free_result(res);
            return -1;
        }
        pthread_mutex_unlock(mutex);
        send(netfd, &response.type, sizeof(MSG_TYPE), MSG_NOSIGNAL);
        send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
        free(parent);
        free(name);
        mysql_free_result(res);
        return 0;
    }

    //不存在同路径的表项，直接插入这个新目录
    bzero(sql, sizeof sql);
    snprintf(sql, sizeof sql, "select user_name,path from fd_data where id = %d and is_delete = 0",trueid);
    printf("%s\n", sql);
    mysql_query(mysql, sql);
    MYSQL_RES *rows = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(rows);

    bzero(sql, sizeof sql);
    char buf[2048] = {0};
    snprintf(buf, sizeof buf, "%s/%s",row[1],name);
    printf("buf\n");
    snprintf(sql, sizeof sql, "insert into fd_data (file_dir_name,user_name,p_id,file_dir_type,path,is_delete) values('%s','%s',%d,'%d','%s',%d)",name, row[0],trueid, is_Dir, buf, 0);
    printf("%s\n", sql);
    if (mysql_query(mysql, sql)) {
        //测试用
        fprintf(stderr, "Insert failed: %s\n", mysql_error(mysql));
    } else {
        printf("Inserted, new id = %llu\n",(unsigned long long)mysql_insert_id(mysql));
    }
    //准备send数据
    response.type = MKDIR_SUCCESS;
    response.args_len = 0;
    pthread_mutex_lock(mutex);
    int true_user_id = pclient_info[netfd].belongs_to_userid;
    if(true_user_id != user_id) {
        printf("发送该请求的用户已断开连接，以上操作无效!\n");
        pthread_mutex_unlock(mutex);
        free(parent);
        free(name);
        mysql_free_result(res);
        return -1;
    }
    pthread_mutex_unlock(mutex);
    send(netfd, &response.type, sizeof(MSG_TYPE), MSG_NOSIGNAL);
    send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
    free(parent);
    free(name);
    mysql_free_result(res);
    return 0;
}





int server_rmdir(MYSQL *mysql, int args_len, char *args, int netfd, Client_info *pclient_info, pthread_mutex_t *mutex, int now_path_id, int user_id){
    char op_args[256];
    sprintf(op_args, "%s %s", "RMDIR", args);
    
    ResponsePackage response;
    bzero(&response, sizeof response);
    char sql[2048] = {0};
    char args_buf[1024] = {0};
    memcpy(args_buf, args, args_len);



    char truepath[256] = {0};
    char *parent = NULL, *name = NULL;
    //找到目录名字
    if (split_path(args, &parent, &name) != 0) {
        fprintf(stderr, "路径校验失败\n");
        free(parent); free(name);
        return 1;
    }
    printf("%s,%s\n", parent, name);
    if(getTruePath(user_id, now_path_id, parent, args_len, mysql, &response, truepath, netfd)){
        return -1;
    }
    int trueid = 0;
    bzero(sql, sizeof(sql));
       snprintf(sql, sizeof sql, "select id from fd_data where path = '%s' and file_dir_type = %d and is_delete = 0",truepath,is_Dir);
       printf("%s\n", sql);
       mysql_query(mysql, sql);
       MYSQL_RES *res = mysql_store_result(mysql);
       MYSQL_ROW row_pre = mysql_fetch_row(res);
       unsigned long num_rows = mysql_num_rows(res);
       printf("%s\n", row_pre[0]);
       trueid = atoi(row_pre[0]);
       printf("查到 %lu 行\n", num_rows);


    //1.查找数据库的当前目录有没有这个目录
    //  没有：报错没有这个目录
    snprintf(sql, sizeof sql, "select id,is_delete from fd_data "
             "where p_id = %d and file_dir_name = '%s' and file_dir_type = %d and is_delete = 0",trueid , name,is_Dir);
    printf("%s\n", sql);
    mysql_query(mysql, sql);
    res = mysql_store_result(mysql);
    row_pre = mysql_fetch_row(res);
    num_rows = mysql_num_rows(res);
    //2.没有：send错误包，并打印错误原因
    if(num_rows == 0){
        response.type = DIR_ERR;
        snprintf(response.args_val, sizeof response.args_val, "This directory does not exist\n");
        response.args_len = strlen (response.args_val);
        printf("%s\n", response.args_val);
        pthread_mutex_lock(mutex);
        int true_user_id = pclient_info[netfd].belongs_to_userid;
        if(true_user_id != user_id) {
            printf("发送该请求的用户已断开连接，以上操作无效!\n");
            pthread_mutex_unlock(mutex);
            return -1;
        }
        pthread_mutex_unlock(mutex);
        send(netfd, &response.type, sizeof(MSG_TYPE), MSG_NOSIGNAL);
        send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
        send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);
        return -1;
        //3.如果存在该目录，查看这个目录是否为空，空：删；不空返回不空提示
    }else if(num_rows != 0){
        snprintf(sql, sizeof sql, "select id,is_delete from fd_data "
                 "where p_id = %d and is_delete = 0",atoi(row_pre[0]));
        printf("%s\n", sql);
        mysql_query(mysql, sql);
        res = mysql_store_result(mysql);
        num_rows = mysql_num_rows(res);
        if(num_rows == 0){
            bzero(sql, sizeof sql);
            snprintf(sql, sizeof sql, "update fd_data set is_delete = 1 where id = %d; ",atoi(row_pre[0]));
            printf("%s\n", sql);
            mysql_query(mysql, sql);
            //准备send数据
            response.type = RMDIR_SUCCESS;
            response.args_len = 0;
            pthread_mutex_lock(mutex);
            int true_user_id = pclient_info[netfd].belongs_to_userid;
            if(true_user_id != user_id) {
                printf("发送该请求的用户已断开连接，以上操作无效!\n");
                pthread_mutex_unlock(mutex);
                return -1;
            }
            pthread_mutex_unlock(mutex);
            send(netfd, &response.type, sizeof(MSG_TYPE), MSG_NOSIGNAL);
            send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
        }else{
            response.type = DIR_ERR;
            snprintf(response.args_val, sizeof response.args_val, "The directory is not empty\n");
            response.args_len = strlen (response.args_val);
            pthread_mutex_lock(mutex);
            int true_user_id = pclient_info[netfd].belongs_to_userid;
            if(true_user_id != user_id) {
                printf("发送该请求的用户已断开连接，以上操作无效!\n");
                pthread_mutex_unlock(mutex);
                return -1;
            }
            pthread_mutex_unlock(mutex);
            send(netfd, &response.type, sizeof(MSG_TYPE), MSG_NOSIGNAL);
            send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
            send(netfd, &response.args_val, response.args_len, MSG_NOSIGNAL);
        }
    }
    return 0;
}






//单元测试
/* int main(int argc, char **argv){ */
/*     ARGS_CHECK(argc, 2); */
/*     MYSQL *mysql = mysql_init(NULL); */
/*     MYSQL *ret = mysql_real_connect(mysql, "localhost", "root", "031178514530", "user_base", 0, NULL, 0 ); */
/*     if(ret == NULL){ */
/*         fprintf(stderr, "%s:%s\n", "mysql_real_connect", mysql_error(mysql)); */
/*     } */
/*     /1* server_ls(mysql, 0, NULL, 4, 1); *1/ */
/*     /1* server_mkdir(mysql, 6,"666666",4,1); *1/ */
/*     server_rmdir(mysql, 6,"666666",4,1); */
/*  } */
